//
//  NTHttpRequest.m
//  SGShow
//
//  Created by fanshijian on 15-3-10.
//  Copyright (c) 2015年 fanshijian. All rights reserved.
//

#import "NTHttpRequest.h"

@implementation NTHttpRequest
@synthesize requestName = _requestName;
@synthesize responseData;

- (void)executeHttpRequest:(NSString *)url
               requestName:(NSString *)requestName
                    method:(NTRequestMethod)methodType
                    params:(id)params
                     block:(void (^)(NTHttpRequest *networkRequest, NSError *error))block {
    NSLog(@"------>>url:%@",url);
    [self setNetworkActivityStart];
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // something
        // 主线程执行：
        dispatch_async(dispatch_get_main_queue(), ^{
            // something
            if (![requestName isEqualToString:UpdateVersion]) {
//                [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//                [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES afterDelay:30];
            }
            
        });
    });
    if (methodType == NTRequestMethodGET) {
        // get请求
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
            NSLog(@"GET JSON: %@", responseObject);
            
            self.requestName = requestName;
            self.responseData = responseObject;
            [self setNetworkActivityEnd];
            if (block) {
                block(self,nil);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"GET Error: %@", error);
            [self setNetworkActivityEnd];
//            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
            if (block) {
                block(nil,error);
            }
            
            if (kNetworkNotReachability) {
                [[MessShowView share] showWithMess:@"网络不给力"];
                
            }else {
//                [[MessShowView share] showWithMess:@"链接服务器失败"];
            }
            
        }];
        
    }else {
        // post请求
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer]; // json请求
        [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            DLog(@"POST JSON: %@", responseObject);
//            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
            self.requestName = requestName;
            self.responseData = responseObject;
            [self setNetworkActivityEnd];
            if (block) {
                block(self,nil);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"POST Error: %@  operation >> %@", error,operation.responseString);
//            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
            [self setNetworkActivityEnd];
            if (block) {
                block(nil,error);
            }
        }];
    }
}

- (void)uploadHttpRequest:(NSString *)url
              requestName:(NSString *)requestName
                   method:(NTRequestMethod)methodType
                   params:(id)params
                     data:(NSData *)data
                    block:(void (^)(NTHttpRequest *networkRequest, NSError *error))block {
    NSLog(@"upload url:%@",url);
    [self setNetworkActivityStart];
    if (methodType == NTRequestMethodGET) {
        // 暂时没有
    }else {
        // post请求
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//        manager.requestSerializer = [AFJSONRequestSerializer serializer]; // json请求
        [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//            NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"test.jpg" withExtension:nil];
            // 要上传保存在服务器中的名称
            // 使用时间来作为文件名 2014-04-30 14:20:57.png
            // 让不同的用户信息,保存在不同目录中
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置日期格式
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *fileName = [formatter stringFromDate:[NSDate date]];
            
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"UPLOAD POST JSON: %@", responseObject);
            self.requestName = requestName;
            self.responseData = responseObject;
            [self setNetworkActivityEnd];
            if (block) {
                block(self,nil);
            }
            
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"POST Error: %@", error);
            [self setNetworkActivityEnd];
            if (block) {
                block(nil,error);
            }
        }];
    }
}
-(void)postImgWithParam:(NSDictionary*)dic requestUrl:(NSString*)url dataArr:(NSArray*)arr block:(void (^)(NTHttpRequest *networkRequest, NSError *error))block
{
    [self setNetworkActivityStart];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // something
        // 主线程执行：
        dispatch_async(dispatch_get_main_queue(), ^{
            // something
//            [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
//            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES afterDelay:30];
        });
    });
    
    NSString *str=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:str parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (arr) {
            UIImage *eachImg = [arr objectAtIndex:0];
            NSData *eachImgData = UIImageJPEGRepresentation(eachImg, 0.05);
            [formData appendPartWithFileData:eachImgData name:@"file" fileName:@"file" mimeType:@"image/jpeg"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        self.responseData = responseObject;
//        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        block(self,nil);
        [self setNetworkActivityEnd];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        block(nil,error);
        [self setNetworkActivityEnd];
    }];
}
- (void)setNetworkActivityStart {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)setNetworkActivityEnd {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

@end
